using System;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Seaskyer.WebApp.Utility.BigUpload
{
	/// <summary>
	/// 
	/// </summary>
	public class UploadHelper
	{
		#region Filds

		private string guid;
		private string script;

		#endregion

		#region Properties

		/// <summary>
		/// Set temporary folder for upload files.
		/// </summary>
		/// <param name="folderPath"></param>
		/// <returns></returns>
		public void SetUploadFolder(string folderPath)
		{
			if (!Path.IsPathRooted(folderPath))
			{
				if (this.guid != string.Empty)
				{
					Utils.GetContext().Application.Remove(("_UploadGUID_" + this.guid));
				}

				throw new IOException("Invaild path.");
			}
			if (!Directory.Exists(folderPath))
			{
				if (this.guid != string.Empty)
				{
					Utils.GetContext().Application.Remove(("_UploadGUID_" + this.guid));
				}

				throw new Exception("Special path does not exsit.");
			}

			((Page) Utils.GetContext().Handler).RegisterHiddenField("Sunrise_Web_Upload_UploadFolder", folderPath);
		}

		#endregion

		/// <summary>
		/// 
		/// </summary>
		public UploadHelper()
		{
			#region Script string

			this.script = String.Empty;
			if(Utils.IsAccordantBrowser())
			{
				script = @"
					<script language=javascript>
					<!--
					url='${url}$';
					var submited = false;
					function openProgress()
					{
						if(!submited)
						{
							var ary = document.getElementsByTagName('INPUT');
							var openBar = false;
							for(var i=0;i<ary.length;i++)
							{
								var obj = ary[i];
								if(obj.type  == 'file')
								{
									if(obj.value != '')
									{
										openBar = true;
										break;
									}
								}
							}
							if(openBar)
							{
								window.showModelessDialog(url, window, 'status:no;help:no;resizable:no;scroll:no;dialogWidth:398px;dialogHeight:200px');
								submited = true;
							}
							return true;
						}
						else
						{
							event.srcElement.disabled = true;
							return false;
						}
					}
					//-->
					</script>";
			}
			else
			{
				script = @"
					<script language=javascript>
					<!--
					url='${url}$';
					var submited = false;
					function openProgress()
					{
						if(!submited)
						{
							var ary = document.getElementsByTagName('INPUT');
							var openBar = false;
							for(var i=0;i<ary.length;i++)
							{
								var obj = ary[i];
								if(obj.type  == 'file')
								{
									if(obj.value != '')
									{
										openBar = true;
										break;
									}
								}
							}
							if(openBar)
							{
								var swd = window.screen.availWidth;
								var sht = window.screen.availHeight;
								var wd = 398;
								var ht =170;
								var left = (swd-wd)/2;
								var top = (sht-ht)/2;
								window.open(url,'_blank','status=no,toolbar=no,menubar=no,location=no,height='+ht+',width='+wd+',left='+left+',top='+top, true);
								submited = true;
							}
							return true;
						}
						else
						{
							event.srcElement.disabled = true;
							return false;
						}
					}
					//-->
					</script>";
			}

			#endregion

			this.guid = string.Empty;
		}

		/// <summary>
		/// Get a uploaded file.
		/// </summary>
		/// <param name="name"></param>
		/// <returns></returns>
		public static UploadFile GetUploadFile(string name)
		{
			UploadFile uploadFile = new UploadFile(name);

			return (uploadFile.FilePath == string.Empty) ? null : uploadFile;
		}

		/// <summary>
		/// Get all uploaded files.
		/// </summary>
		/// <param name="name"></param>
		/// <returns></returns>
		public static UploadFileCollection GetUploadFileList(string name)
		{
			UploadFileCollection uploadFiles = new UploadFileCollection();

			string content = Utils.GetContext().Request[name];
			if ((content == null) || (content == string.Empty))
			{
				return uploadFiles;
			}
			else
			{
				string[] contentArray = content.Split(',');

				for (int i = 0; i < contentArray.Length; i++)
				{
					string curContent = contentArray[i];
					uploadFiles.Add(new UploadFile(curContent));
				}

			}

			return uploadFiles;
		}

		/// <summary>
		/// Register progress bar to a button.
		/// </summary>
		/// <param name="uploadButton"></param>
		/// <param name="causesValidation"></param>
		public void RegisterProgressBar(Button uploadButton, bool causesValidation)
		{
			if (causesValidation)
			{
				uploadButton.CausesValidation = false;
				uploadButton.Attributes["onclick"] = "if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate();if(!Page_BlockSubmit){openProgress();}";
			}
			else
			{
				uploadButton.Attributes["onclick"] = "openProgress();";
			}

			this.guid = Guid.NewGuid().ToString();
			string progressUrl = "progress.ashx?UploadID=" + this.guid;

			Page page = ((Page) Utils.GetContext().Handler);

			page.RegisterHiddenField("Sunrise_Web_Upload_UploadGUID", this.guid);

			this.script = this.script.Replace("${url}$", progressUrl);
			page.RegisterStartupScript("ProgressScript", this.script);

			UploadStatus uploadStatus = new UploadStatus();
			page.Application.Add(("_UploadGUID_" + this.guid), uploadStatus);
		}

	}

}